package com.hp.ssmp.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hp.ssmp.entity.TUser;
import com.hp.ssmp.service.UserService;
import com.hp.ssmp.util.R;
import com.hp.ssmp.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/login")
public class LoginController {

    @Resource
    private UserService userService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @GetMapping("/doLogin")
    public R login(String usercode,String password){
        TUser user = userService.login(usercode, password);
        if(null != user) {
            if(user.getStatus() == 1) {
                user.setPassword(null);
                user.setSalt(null);
                String token = UUID.randomUUID().toString().replace("-","");
                redisTemplate.opsForValue().set(token,user,1800, TimeUnit.SECONDS);
                Map<String,Object> map = new HashMap<String,Object>();
                map.put("token",token);
                map.put("user",user);
                return R.success(map);
            }else{
                return R.error(StatusCode.STATUS_FREEZE_ERROR, "用户账号已被冻结");
            }
        }else{
            return R.error(StatusCode.PWD_ERROR, "用户名或密码错误");
        }
    }
}
